package com.budwk.app.sqfwV2.component;

import cn.hutool.core.bean.BeanUtil;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.budwk.app.common.component.DictComponent;
import com.budwk.app.common.config.AppException;
import com.budwk.app.dfxyWechatMP.DfxyWeChatMPUtils;
import com.budwk.app.sms.service.ZtSmsService;
import com.budwk.app.sqfw.constants.CommonConstants;
import com.budwk.app.sqfw.constants.SqfwFormSummaryConstants;
import com.budwk.app.sqfw.constants.SqfwWebSocketMsgConstants;
import com.budwk.app.sqfw.enums.DownLoadFileNameEnum;
import com.budwk.app.sqfw.enums.SqfwFormSummaryFieldEnum;
import com.budwk.app.sqfw.enums.SupportBusinessTypeEnum;
import com.budwk.app.sqfw.models.Sqfw_Sms_Msg;
import com.budwk.app.sqfw.models.Sqfw_completeflow;
import com.budwk.app.sqfw.models.Sqfw_formSummary_new;
import com.budwk.app.sqfw.models.Sqfw_form_summary_pdf;
import com.budwk.app.sqfw.services.SqfwFormSummaryPdfService;
import com.budwk.app.sqfw.services.SqfwFormsummaryNewService;
import com.budwk.app.sqfw.services.SqfwSmsMsgService;
import com.budwk.app.sqfw.vo.GenerateWordAndPdfUrlVO;
import com.budwk.app.sqfwDoc.bo.PdfGenerateRes;
import com.budwk.app.sqfwDoc.codeGenerator.bo.PdfCreatedBridgeBO;
import com.budwk.app.sqfwDoc.codeGenerator.impl.SqfwTemplatePdfCommonService;
import com.budwk.app.sqfwDoc.codeGenerator.pdfGenerate.AbstractCustomerPdfCreateField;
import com.budwk.app.sqfwDoc.codeGenerator.pdfGenerate.BasePdfParamDTO;
import com.budwk.app.sqfwDoc.codeGenerator.pdfGenerate.BaseTemplatePdfGenerator;
import com.budwk.app.sqfwDoc.codeGenerator.pdfGenerate.SqfwPdfCreateCommonBO;
import com.budwk.app.sqfwV2.component.centuryCity.CenturyCitySecurityComponent;
import com.budwk.app.sqfwV2.dto.dto.ExtraProblemVo;
import com.budwk.app.sqfwV2.dto.dto.FireSafetyOnDayingRoadPdfDTO;
import com.budwk.app.sqfwV2.dto.dto.centuryCity.SafeCheckTaskParamDataDTO;
import com.budwk.app.sqfwV2.dto.dto.dayingRoad.ProblemBaseVo;
import com.budwk.app.sqfwV2.dto.entity.SqfwShopsBaseInfo;
import com.budwk.app.sqfwV2.enums.RectificateTimeEnum;
import com.budwk.app.sqfwV2.enums.dayingRoad.FoodSupervisionRecordsEnum;
import com.budwk.app.sqfwV2.enums.dayingRoad.KeySafetyIndustriesEnum;
import com.budwk.app.sqfwV2.enums.dayingRoad.OtherPatrolContentsEnum;
import com.budwk.app.sqfwV2.enums.lanHuaDu.LanHuaDuFileServiceEnum;
import com.budwk.app.sqfwV2.generator.dayingRoadPdf.*;
import com.budwk.app.sqfwV2.service.ShopsBaseInfoService;
import com.budwk.app.sys.services.SysUserService;
import com.budwk.app.util.DateUtils;
import com.budwk.app.util.StrUtil;
import com.budwk.app.util.poiUtils.nutzBeanUtils.NutzIocUtils;
import com.budwk.starter.security.utils.SecurityUtil;
import com.deepoove.poi.XWPFTemplate;
import com.google.common.collect.Lists;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.nutz.ioc.loader.annotation.Inject;
import org.nutz.ioc.loader.annotation.IocBean;

import java.io.ByteArrayOutputStream;
import java.time.Duration;
import java.time.LocalDateTime;
import java.util.*;
import java.util.stream.Collectors;

import static com.budwk.app.util.poiUtils.CommonFormOfficeUtils.wordToPdfAndUpload;
import static com.budwk.app.util.poiUtils.CommonFormOfficeUtils.wordUpload;

/**
 * 本代码由代码生成器生成，版本号1.0
 */

@Slf4j
@IocBean
public class FireSafetyOnDayingRoadPdfService extends SqfwTemplatePdfCommonService {

    @Inject
    private SqfwFormsummaryNewService sqfwFormsummaryNewService;
    @Inject
    private ShopsBaseInfoService shopsBaseInfoService;
    @Inject
    private ZtSmsService ztSmsService;

    @Override
    public AbstractCustomerPdfCreateField getPdfCreateField(Sqfw_formSummary_new formSummary) {
        return JSON.parseObject(formSummary.getParamData(), FireSafetyOnDayingRoadPdfDTO.class);
    }

    /**
     * 第五张表中的需要的类型，详情见 {@link SqfwFormSummaryConstants}
     *
     * @return 返回数据
     */
    @Override
    public String getSummaryType() {
        return SupportBusinessTypeEnum.SAFETY_CHECK.getName();
    }

    /**
     * 当pdf生成成功的时候，sock发送什么样的消息至前端
     * 参照{@link SqfwWebSocketMsgConstants}
     *
     * @return 结果
     */
    @Override
    public String getPdfCreateSocketType() {
        return SqfwWebSocketMsgConstants.work_flow_pdf_created;
    }

    /**
     * 创建下载文件的名称
     * 可以参照 {@link DownLoadFileNameEnum}
     * 注意！！！ 不用加上.pdf或者.word后缀
     *
     * @param completeFlow   工作流
     * @param formSummaryNew 表单数据
     * @return 结果
     */
    @Override
    protected String getDownloadFileName(Sqfw_completeflow completeFlow, Sqfw_formSummary_new formSummaryNew) {
        return DownLoadFileNameEnum.SAFETY_INVESTIGATE_RENOVATE.getName();
    }

    @Override
    protected void customerPopularPdfCreateParam(SqfwPdfCreateCommonBO pdfCreateCommonBO, Sqfw_completeflow completeFlow, Sqfw_formSummary_new formSummary) {

    }

    @Override
    protected List<BaseTemplatePdfGenerator> getPdfGenerator(Sqfw_completeflow completeFlow, Sqfw_formSummary_new formSummary) {
        List<BaseTemplatePdfGenerator> generatorList = Lists.newArrayList();
        generatorList.add(new SmallBusinessGenerator());
        generatorList.add(new CateringPremisesSafetyPdfGenerator());
        generatorList.add(new BottleGasSafetyPdfGenerator());
        generatorList.add(new FoodSupInsRecordPdfGenerator());
        generatorList.add(new SafetyRiskStandingPdfGenerator());
        generatorList.add(new PictureGenerator());
        // 在这里添加自己的generator
        return generatorList;
    }

    private void checkParam(Sqfw_formSummary_new formSummary, FireSafetyOnDayingRoadPdfDTO pdfDTO) {
        if (formSummary == null) {
            throw new AppException("请求参数为空！");
        }
        if (StringUtils.isEmpty(formSummary.getParamData())) {
            throw new AppException("请求参数paramData为空！");
        }
        String mainBusinessScope = pdfDTO.getMainBusinessScope();
        if (StringUtils.isNotEmpty(mainBusinessScope)) {
            String dictName = DictComponent.getDictName(mainBusinessScope, null);
            if (StringUtils.isEmpty(dictName)) {
                throw new AppException("主要经营范围参数不正确，请检查！");
            }
        }
    }

    private SafeCheckTaskParamDataDTO handleSafeCheckTaskParamDataDTO(SafeCheckTaskParamDataDTO dataDTO) {
        dataDTO.setRiskLevel(DayingRoadPdfComponent.getDictName(dataDTO.getRiskLevelCode(), null));
        dataDTO.setRectificationType(RectificateTimeEnum.getNameByCode(dataDTO.getRectificationTypeCode()));
        return dataDTO;
    }

    private void buildKeySafetyIndustriesText(FireSafetyOnDayingRoadPdfDTO pdfDTO, FireSafetyOnDayingRoadPdfDTO lastDataPdfDTO) {
        // 1 初始化数据
        List<SafeCheckTaskParamDataDTO> datas = initData(pdfDTO.getKeySafetyIndustries(), KeySafetyIndustriesEnum.getAllDefaults());
        pdfDTO.setKeySafetyIndustries(datas);
        // 2 找出存在的问题
        // 组装获取问题默认值
        List<ProblemBaseVo> problemBaseVoDefaults = KeySafetyIndustriesEnum.getProblemBaseVoDefaults();

        List<SafeCheckTaskParamDataDTO> lastExistProblems = lastDataPdfDTO != null ? lastDataPdfDTO.getExtraKeyParam().getExistProblems() : null;
        pdfDTO.setExtraKeyParam(getExtraProblemVo(problemBaseVoDefaults, datas, lastExistProblems));
    }

    private void buildOtherPatrolContentsContent(FireSafetyOnDayingRoadPdfDTO pdfDTO, FireSafetyOnDayingRoadPdfDTO lastDataPdfDTO) {
        // 组装获取问题默认值
        List<ProblemBaseVo> defaults = OtherPatrolContentsEnum.getProblemBaseVoDefaults();
        // 移除第24个问题
        defaults.removeIf(e -> e.getCode().equals(OtherPatrolContentsEnum.TWENTYFORE.getCode()));
        // 取出前端传递数值
        List<SafeCheckTaskParamDataDTO> otherPatrolContents = pdfDTO.getOtherPatrolContents();
        // 获取上次存在的问题数据
        List<SafeCheckTaskParamDataDTO> lastExistProblems = lastDataPdfDTO != null ? lastDataPdfDTO.getExtraOtherParam().getExistProblems() : null;
        pdfDTO.setExtraOtherParam(getExtraProblemVo(defaults, otherPatrolContents, lastExistProblems));
    }

    private void buildFoodContent(FireSafetyOnDayingRoadPdfDTO roadPdfDTO, FireSafetyOnDayingRoadPdfDTO lastDataPdfDTO) {
        // 1 初始化数据
        List<SafeCheckTaskParamDataDTO> datas = initData(roadPdfDTO.getFoodSupervisionRecords(), FoodSupervisionRecordsEnum.getAllDefaults());
        roadPdfDTO.setFoodSupervisionRecords(datas);
        // 2 找出存在的问题
        List<ProblemBaseVo> defaults = FoodSupervisionRecordsEnum.getProblemBaseVoDefaults();
        List<SafeCheckTaskParamDataDTO> lastExistProblems = lastDataPdfDTO != null ? lastDataPdfDTO.getExtraFoodParam().getExistProblems() : null;
        roadPdfDTO.setExtraFoodParam(getExtraProblemVo(defaults, datas, lastExistProblems));
    }

    /**
     * 提交前的操作
     *
     * @param formSummary formSummary 前端传递过来的参数
     */
    @Override
    protected void beforeInsertForSummary(Sqfw_formSummary_new formSummary) {
        log.info("fireSafetyOnDayingRoadPdfService beforeInsertForSummary param:: {}", JSONObject.toJSONString(formSummary));
        beforeIForSummary(formSummary);
        // 入库商铺
        SqfwShopsBaseInfo shopsBase = JSONObject.toJavaObject(JSONObject.parseObject(formSummary.getParamData()), SqfwShopsBaseInfo.class);
        shopsBase.setServiceType(SupportBusinessTypeEnum.SAFETY_CHECK.getCode());
        SqfwShopsBaseInfo sp = shopsBaseInfoService.insertOrUpdateData(shopsBase, formSummary);
        formSummary.setShopsBaseInfoId(sp.getId());
    }

    private void beforeIForSummary(Sqfw_formSummary_new formSummary) {
        log.info("fireSafetyOnDayingRoadPdfService beforeInsertForSummary param:: {}", JSONObject.toJSONString(formSummary));
        FireSafetyOnDayingRoadPdfDTO pdfDTO = JSONObject.parseObject(formSummary.getParamData(), FireSafetyOnDayingRoadPdfDTO.class);
        checkParam(formSummary, pdfDTO);
        // 1 重点安全排查行业参数校验
        // 2 获取上一次的数据
        Sqfw_formSummary_new lastData = CenturyCitySecurityComponent.queryLastData(formSummary, SupportBusinessTypeEnum.SAFETY_CHECK.getName());
        FireSafetyOnDayingRoadPdfDTO lastDataPdfDTO = null;
        if (lastData != null) {
            pdfDTO.setLastSummaryId(lastData.getId());
            lastDataPdfDTO = JSONObject.parseObject(lastData.getParamData(), FireSafetyOnDayingRoadPdfDTO.class);
        } else {
            pdfDTO.setLastSummaryId(null);
        }
        buildKeySafetyIndustriesText(pdfDTO, lastDataPdfDTO);
        // 是否配备灭火器
        // 1 初始化数据
        pdfDTO.setOtherPatrolContents(initData(pdfDTO.getOtherPatrolContents(), OtherPatrolContentsEnum.getAllDefaults()));
        FireIssusComponent.buildEquippedFire(pdfDTO);
        // 25个问题  其余巡查内容25个问题默认值
        buildOtherPatrolContentsContent(pdfDTO, lastDataPdfDTO);
        // 3 ■【食品监督检查记录】九个问题默认选项为【是】。
        buildFoodContent(pdfDTO, lastDataPdfDTO);
        // 5 报警器使用是否正常(报警器大于0显示)
        SafeCheckTaskParamDataDTO p = pdfDTO.getIsAlarmNormal();
        if (p == null) {
            p = new SafeCheckTaskParamDataDTO();
            p.setKey("-").setFields("isAlarmNormal");
            pdfDTO.setIsAlarmNormal(p);
        }
        if (StringUtils.isEmpty(pdfDTO.getLiquefiedGasUsage())) {
            pdfDTO.setLiquefiedGasUsage("1");
        }
        // 6 检查情况 检查状态
        buildInspection(formSummary, pdfDTO);
        // 住人问题
        FireIssusComponent.buildAccommodatePeopleVo(pdfDTO);
        // 是否搭建夹层
        FireIssusComponent.buildSandwichingVo(pdfDTO);
        // 电气线路情况
        FireIssusComponent.buildElectricalCircuitSituation(pdfDTO);
        // 电动自行车使用情况
        FireIssusComponent.buildElectricBicyclesUse(pdfDTO);
        // 明火、高温加热、取暖设备等的使用地点
        FireIssusComponent.buildFireHighUsageArea(pdfDTO);
        // 是否存放易燃易爆危险品
        FireIssusComponent.buildCombustiblEexplosive(pdfDTO);
        // 其他隐患
        FireIssusComponent.buildOtherDanger(pdfDTO);
        // 消防设施的其他问题
        FireIssusComponent.buildFireOtherIssues(pdfDTO);
        // 是否存在隐患
        List<SafeCheckTaskParamDataDTO> fireIssues = ProblemComponent.getFireIssues(pdfDTO);
        pdfDTO.setIsExistDanger(false).setIsRectified(1);
        if (fireIssues.size() > 0) {
            pdfDTO.setIsRectified(2).setIsExistDanger(true);
            long count = fireIssues.stream().filter(e -> e.getIsRectification().equals(false)).count();
            String fireIssueStr = fireIssues.stream().map(SafeCheckTaskParamDataDTO::getProblemDesc).collect(Collectors.joining(""));
            pdfDTO.setIsRectified(count > 0 ? 3 : 2)
                    .setExistDangerStr(fireIssueStr)
                    .setFireIssues(fireIssues);
        } else {
            pdfDTO.setExistDangerStr(null).setFireIssues(null);
        }
        // 检查时间
        LocalDateTime inspectionDate = pdfDTO.getInspectionDate();
        if (inspectionDate != null) {
            formSummary.setFillDate(DateUtils.toDateByLocalDateTime(inspectionDate));
        }
        FireSafetyOnDayingRoadPdfDTO f = StrUtil.serializerData(FireSafetyOnDayingRoadPdfDTO.class, pdfDTO);
        log.info("fireSafetyOnDayingRoadPdfService beforeInsertForSummary roadPdfDTO end: {}", JSONObject.toJSONString(f));
        formSummary.setParamData(JSONObject.toJSONString(f));
    }


    private void buildInspection(Sqfw_formSummary_new formSummary, FireSafetyOnDayingRoadPdfDTO roadPdfDTO) {
        // 已停业不做任何修改
        if (StringUtils.isNotEmpty(formSummary.getCheckStatus())) {
            if (formSummary.getCheckStatus().equals(SqfwFormSummaryFieldEnum.CHECK_STATUS_CLOSED.getCode())) {
                return;
            }
        }
        // 1 按照商铺名称和地址去查询是否所有数据
        List<Sqfw_formSummary_new> summarys = sqfwFormsummaryNewService.queryByPlaceAndAddress(roadPdfDTO.getPlaceName(), roadPdfDTO.getAddress(),
                SupportBusinessTypeEnum.SAFETY_CHECK.getName(), formSummary.getUnitId());
        LocalDateTime start = roadPdfDTO.getInspectionDate();//最后时间
        Duration duration = Duration.between(start, LocalDateTime.now());
        formSummary.setCheckStatus(SqfwFormSummaryFieldEnum.check_status_init.getCode())
                .setInspectionSituation(duration.toDays() > 30 ? SqfwFormSummaryFieldEnum.CHECK_SITUATION_YES.getCode() :
                        SqfwFormSummaryFieldEnum.CHECK_SITUATION_NO.getCode());
        if (summarys.size() > 0) {
            // 历史数据全部修改为 未超时 已检查
            summarys.forEach(e -> e.setCheckStatus(SqfwFormSummaryFieldEnum.check_status_checked.getCode())
                    .setInspectionSituation(SqfwFormSummaryFieldEnum.CHECK_SITUATION_NO.getCode())
                    .setUpdateBy(SecurityUtil.getUserId())
                    .setUpdateDate(new Date())
                    .setUpdateUserName(SecurityUtil.getUserUsername()));
            sqfwFormsummaryNewService.updateIgnoreNull(summarys);
        }
    }

    private void checkSafeCheckTaskParamDataDTO(List<SafeCheckTaskParamDataDTO> contents) {
        for (SafeCheckTaskParamDataDTO safe : contents) {
            if (StringUtils.isEmpty(safe.getFields())) {
                log.info("safeCheckTaskParamDataDTO initData safe: {}", JSONObject.toJSONString(safe));
                throw new AppException("字段名不能为空！");
            }
            if (StringUtils.isEmpty(safe.getKey())) {
                log.info("safeCheckTaskParamDataDTO initData safe: {}", JSONObject.toJSONString(safe));
                throw new AppException("字段key不能为空！");
            }
            if (!CommonConstants.TRUE.equals(safe.getKey()) && !CommonConstants.FALSE.equals(safe.getKey())) {
                throw new AppException("字段key只能传递true或者false！");
            }
        }

    }

    private List<SafeCheckTaskParamDataDTO> initData(List<SafeCheckTaskParamDataDTO> contents, List<SafeCheckTaskParamDataDTO> allDefaults) {
        if (contents == null || contents.size() == 0) {
            return allDefaults;
        }
        checkSafeCheckTaskParamDataDTO(contents);
        List<SafeCheckTaskParamDataDTO> datas = new ArrayList<>();
        // 获取所有的问题默认值
        for (SafeCheckTaskParamDataDTO safe : allDefaults) {
            // 检查是否在默认值中存在
            Optional<SafeCheckTaskParamDataDTO> optional = contents.stream().filter(e -> e.getFields().equals(safe.getFields())).findFirst();
            if (optional.isEmpty()) {
                // 不存在，将默认值加入到数据中存储
                datas.add(safe);
                continue;
            }
            // 存在 设置编号和描述信息
            SafeCheckTaskParamDataDTO s = optional.get();
            s.setRiskDesc(safe.getRiskDesc()).setRiskCode(safe.getRiskCode());
            datas.add(handleSafeCheckTaskParamDataDTO(s));
        }
        return datas;
    }

    /**
     * 获取额外的参数
     *
     * @param defaults 默认值
     * @param datas    数据值
     * @return
     */
    private ExtraProblemVo getExtraProblemVo(List<ProblemBaseVo> defaults, List<SafeCheckTaskParamDataDTO> datas, List<SafeCheckTaskParamDataDTO> lastExistProblems) {
        // 1 获取存在的问题选项
        List<SafeCheckTaskParamDataDTO> existProblems = getExistProblems(datas, defaults);
        List<Integer> existImmediateProblemIds = new ArrayList<>();
        // 遍历上次存在的问题数据
        if (lastExistProblems != null) {
            // 从本次问题中找出上次是期限整改 本次是立即整改的数据
            for (SafeCheckTaskParamDataDTO existProblem : existProblems) {
                if (!RectificateTimeEnum.isNowRectification(existProblem.getRectificationTypeCode())) {
                    continue;
                }
                // 属于立即整改 检查上次的数据是否为期限整改
                Optional<SafeCheckTaskParamDataDTO> optional = lastExistProblems.stream().filter(e -> e.getFields().equals(existProblem.getFields())).findFirst();
                if (optional.isEmpty()) {
                    continue;
                }
                // 上次存在该问题
                SafeCheckTaskParamDataDTO lastSafe = optional.get();
                if (RectificateTimeEnum.isDeadline(lastSafe.getRectificationTypeCode())) {
                    // 上次数据是期限整改
                    existImmediateProblemIds.add(Integer.parseInt(existProblem.getRiskCode()));
                }
            }
        }
        // 2 获取存在的所有有问题的数据
        ExtraProblemVo vo = new ExtraProblemVo();
        // 存在的问题编号
        List<Integer> existProblemIds = existProblems.stream()
                .sorted(Comparator.comparing(SafeCheckTaskParamDataDTO::getRiskCode))
                .map(SafeCheckTaskParamDataDTO::getRiskCode)
                .map(Integer::valueOf)
                .sorted(Comparator.comparing(Integer::valueOf))
                .collect(Collectors.toList());
        // 已整改的问题编号
        List<Integer> existYesProblemIds = existProblems.stream()
                .filter(SafeCheckTaskParamDataDTO::getIsRectification)
                .sorted(Comparator.comparing(SafeCheckTaskParamDataDTO::getRiskCode))
                .map(SafeCheckTaskParamDataDTO::getRiskCode)
                .map(Integer::valueOf)
                .sorted(Comparator.comparing(Integer::valueOf))
                .collect(Collectors.toList());
        // 未整改的问题编号
        List<Integer> existNoProblemIds = existProblems.stream()
                .filter(e -> RectificateTimeEnum.DEADLINE_RECTIFICATION.getCode().equals(e.getRectificationTypeCode()))
                .sorted(Comparator.comparing(SafeCheckTaskParamDataDTO::getRiskCode))
                .map(SafeCheckTaskParamDataDTO::getRiskCode)
                .map(Integer::valueOf)
                .sorted(Comparator.comparing(Integer::valueOf))
                .collect(Collectors.toList());
        // 立即整改的问题编号 （立即整改），统计上一次的期限整改，本次是立即整改的数据
        vo.setExistProblems(existProblems)
                .setExistProblemIds(existProblemIds)
                .setExistYesProblemIds(existYesProblemIds)
                .setExistNoProblemIds(existNoProblemIds)
                .setExistImmediateProblemIds(existImmediateProblemIds.stream().sorted(Comparator.comparing(String::valueOf)).collect(Collectors.toList()))
                .setIsProblemAllOne(existNoProblemIds.size() <= 0);
        return vo;
    }


    /**
     * 获取存在的问题数据
     *
     * @param datas
     * @param defaults
     * @return
     */
    public static List<SafeCheckTaskParamDataDTO> getExistProblems(List<SafeCheckTaskParamDataDTO> datas, List<ProblemBaseVo> defaults) {
        List<SafeCheckTaskParamDataDTO> existProblems = new ArrayList<>();
        for (SafeCheckTaskParamDataDTO d : datas) {
            Optional<ProblemBaseVo> first = defaults.stream().filter(e -> e.getCode().equals(d.getFields())).findFirst();
            if (first.isEmpty()) {
                continue;
            }
            ProblemBaseVo p = first.get();
            //  和默认值一致 属于不存在问题
            if (d.getKey().equals(p.getDefaultValue())) {
                continue;
            }
            d.setIsRectification(RectificateTimeEnum.isNowRectification(d.getRectificationTypeCode())).setProblemDesc(d.getRiskDesc());
            existProblems.add(d);
        }
        return existProblems;
    }

    /**
     * pdf创建成功，更新工作流之后自定义方法
     */
    @Override
    protected void afterCreatePdfSuccess(PdfCreatedBridgeBO pdfCreatedBridgeBO) {
        if (pdfCreatedBridgeBO.getReCreateFlag()) {
            // 不发送短信
            return;
        }
        Sqfw_formSummary_new formSummary = pdfCreatedBridgeBO.getFormSummaryNew();
        FireSafetyOnDayingRoadPdfDTO pdfDTO = JSONObject.parseObject(formSummary.getParamData(), FireSafetyOnDayingRoadPdfDTO.class);
        log.info("daying road afterCreatePdfSuccess sendmsg userId: {} , param: {}", pdfCreatedBridgeBO.getUserId(), pdfDTO.getOperatorTelephone());
        if (StringUtils.isEmpty(pdfDTO.getOperatorTelephone())) {
            return;
        }
        String url = DfxyWeChatMPUtils.generatedDfxyMiniProgramUrl("/pages/user-center/safeList");
        if (StringUtils.isEmpty(url)) {
            return;
        }
        String msgContentStr = "您的安全排查整治表可在微信小程序中进行查看:" + url;
        // wzy 2024-5-29 修改为其他发送方式
        Integer status  = ztSmsService.ztSendSafetyCheckInfoMsg(pdfDTO.getOperatorTelephone(), url);
        if (status == null) {
            return;
        }

        Sqfw_Sms_Msg smsMsg = new Sqfw_Sms_Msg();
        SqfwSmsMsgService sqfwSmsMsgService = NutzIocUtils.getBean(SqfwSmsMsgService.class);

        smsMsg.setName(pdfDTO.getPlaceName())
                .setType(SupportBusinessTypeEnum.SAFETY_CHECK.getName())
                .setStatus(status == 1 ? "成功" : "失败")
                .setAddress(pdfDTO.getAddress())
                .setCreateDate(new Date())
                .setUserName(pdfDTO.getOperator())
                .setPhone(pdfDTO.getOperatorTelephone())
                .setSummaryId(formSummary.getId())
                .setMsg(msgContentStr);
        sqfwSmsMsgService.insert(smsMsg);
        log.info("daying road afterCreatePdfSuccess sendmsg end");
    }

    /**
     * 重新创建pdf之前可以自定义进行操作
     *
     * @param formSummaryNews 表单数据
     */
    @Override
    protected void beforeReGenPdf(Sqfw_formSummary_new formSummaryNews) {
        String paramData = formSummaryNews.getParamData();
        beforeIForSummary(formSummaryNews);
        String paramData1 = formSummaryNews.getParamData();
        if (!paramData.equals(paramData1)) {
            // 修改数据
            sqfwFormsummaryNewService.updateIgnoreNull(formSummaryNews);
        }
    }

    private SqfwPdfCreateCommonBO initSqfwPdfCreateCommonBO(Sqfw_formSummary_new formSummary) {
        FireSafetyOnDayingRoadPdfDTO safeCheckTaskPdfDTO = JSONObject.parseObject(formSummary.getParamData(), FireSafetyOnDayingRoadPdfDTO.class);
        SqfwPdfCreateCommonBO pdfDTO = new SqfwPdfCreateCommonBO();
        pdfDTO.setAbstractCustomerPdfCreateField(safeCheckTaskPdfDTO);
        BasePdfParamDTO basePdfParamDTO = new BasePdfParamDTO();
        BeanUtil.copyProperties(formSummary, basePdfParamDTO);
        basePdfParamDTO.setCreateUserId(formSummary.getCreateBy());
        basePdfParamDTO.setFormSummaryTypeCode(getSummaryType());
        basePdfParamDTO.setCreateUserName(formSummary.getCreateUserName());
        basePdfParamDTO.setCreateUserPhone(formSummary.getCreateUserPhone());
        SysUserService userService = NutzIocUtils.getBean(SysUserService.class);
        basePdfParamDTO.setCreateUserSigUrl(userService.fetch(formSummary.getCreateBy()).getSignatureUrl());
        basePdfParamDTO.setSqfwId(formSummary.getSqfwId());
        Date fillDate = formSummary.getFillDate();
        if (fillDate == null) fillDate = formSummary.getCreateDate();
        basePdfParamDTO.setFillDate(fillDate);
        basePdfParamDTO.setProvince(formSummary.getProvince());
        basePdfParamDTO.setCity(formSummary.getCity());
        basePdfParamDTO.setDistrict(formSummary.getDistrict());
        basePdfParamDTO.setCounty(formSummary.getCounty());
        basePdfParamDTO.setCommunity(formSummary.getCommunity());
        pdfDTO.setBasePdfParamDTO(basePdfParamDTO);
        return pdfDTO;
    }

    public void getPdfGenerateResAfter(List<PdfGenerateRes> pdfGenerateResList, Sqfw_formSummary_new formSummary) {
        if (!LanHudDuComponent.isLHDCity(formSummary.getCreateBy())) {
            return;
        }
        List<LanHuaDuFileServiceEnum> allPdf = LanHuaDuFileServiceEnum.getAllPdf();
        for (LanHuaDuFileServiceEnum serviceEnum : allPdf) {
            try {
                SqfwPdfCreateCommonBO pdfCreateCommonBO = initSqfwPdfCreateCommonBO(formSummary);
                BaseTemplatePdfGenerator generator = serviceEnum.getService();
                boolean isGenerate = generator.pdfCreateConditionCheck(pdfCreateCommonBO);
                if (!isGenerate) {
                    continue;
                }
                XWPFTemplate pdfTemplate = generator.createPdf(pdfCreateCommonBO);
                // 生成pdf后的操作
                ByteArrayOutputStream pdfOS = generator.generatePDFAfter(pdfTemplate, formSummary);
                if (pdfOS == null) {
                    if (pdfTemplate == null) continue;
                    pdfOS = new ByteArrayOutputStream();
                    pdfTemplate.write(pdfOS);
                }
                String fileName = serviceEnum.getFileName();
                GenerateWordAndPdfUrlVO wordVO;
                if (serviceEnum.getCode().equals(LanHuaDuFileServiceEnum.C.getCode())) {
                    wordVO = wordUpload(pdfOS, fileName, formSummary.getUnitName() + formSummary.getType());
                    if (wordVO != null) {
                        wordVO.setUrl(wordVO.getUrl());
                    }
                } else {
                    wordVO = wordToPdfAndUpload(List.of(pdfOS), fileName, formSummary.getUnitName() + formSummary.getType());
                    wordVO.setUrl(wordVO.getPdfUrl());
                }
                // 存储本地数据库
                insertOrUpdatePdf(formSummary,  serviceEnum, wordVO);
            } catch (Exception e) {
                insertOrUpdatePdf(formSummary,  serviceEnum, null);
                log.error("sandu getPdfGenerateResAfter error: ", e);
            }
        }
    }


    private void insertOrUpdatePdf(Sqfw_formSummary_new formSummary, LanHuaDuFileServiceEnum serviceEnum, GenerateWordAndPdfUrlVO wordVO) {
        SqfwFormSummaryPdfService formSummaryPdfService = NutzIocUtils.getBean(SqfwFormSummaryPdfService.class);
        Sqfw_form_summary_pdf summaryPdf = formSummaryPdfService.findBySummaryIdAndIndex(formSummary.getId(), serviceEnum.getLocation());
        if (summaryPdf != null) {
            summaryPdf.setUpdateDate(new Date());
            if (wordVO != null) {
                summaryPdf.setUrl(wordVO.getUrl()).setStatus("2");
            }
            formSummaryPdfService.updateIgnoreNull(summaryPdf);
            return;
        }
        Sqfw_form_summary_pdf formSummaryPdf = initSqfwFormSummaryPdf(formSummary, null);
        formSummaryPdf.setSummaryId(formSummary.getId()).setIndex(serviceEnum.getLocation());
        if (wordVO != null) {
            formSummaryPdf.setUrl(wordVO.getUrl()).setStatus("2");
        } else {
            formSummaryPdf.setStatus("3");
        }
        formSummaryPdfService.insert(formSummaryPdf);
    }


    private Sqfw_form_summary_pdf initSqfwFormSummaryPdf(Sqfw_formSummary_new formSummary, GenerateWordAndPdfUrlVO wordVO) {
        Sqfw_form_summary_pdf formSummaryPdf = new Sqfw_form_summary_pdf();
        formSummaryPdf.setSummaryId(formSummary.getId())
                .setUrl(wordVO != null ? wordVO.getPdfUrl() : null)
                .setCreateDate(new Date())
                .setUpdateDate(new Date());
        return formSummaryPdf;
    }
}
